package com.example.main;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.main.widget.BluetoothConnectCallback;
import com.example.main.widget.BluetoothConnectThread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class BlueToothActivity extends FragmentActivity implements View.OnClickListener {

    private Handler handler = new Handler();

    public static int DEFAULT_VALUE_BULUETOOTH = 1000;

    private static final String TAG = "BlueToothActivity";

    private Button btn_blue_tooth;
    private Button btn_check_new_devices;
    private Button btn_pair;
    private BluetoothAdapter mBluetoothAdapter;
    private List<String> mArrayAdapter = new ArrayList<>();
    private List<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();
    private BluetoothDevice bluetoothDevice = null;
    private BluetoothSocket bluetoothSocket;
    private TextView tv_show;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blue_tooth);

        tv_show = findViewById(R.id.tv_show);
        tv_show.requestFocus();
        tv_show.findFocus();
        tv_show.setFocusable(true);

        btn_blue_tooth = findViewById(R.id.btn_blue_tooth);
        btn_blue_tooth.setOnClickListener(this);

        btn_check_new_devices = findViewById(R.id.btn_check_new_devices);
        btn_check_new_devices.setOnClickListener(this);

        btn_pair = findViewById(R.id.btn_pair);
        btn_pair.setOnClickListener(this);

        registerBlueToothBroadCast();

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {//说明此设备不支持蓝牙操作
            Log.i(TAG, "onCreate: 没有蓝牙");
            btn_blue_tooth.setText("没有蓝牙");
        } else {
            Log.i(TAG, "onCreate: 有蓝牙");
            if (!mBluetoothAdapter.isEnabled()) {
                btn_blue_tooth.setText("打开蓝牙");
                btn_check_new_devices.setVisibility(View.GONE);
            } else {
                btn_blue_tooth.setText("关闭蓝牙");
                btn_check_new_devices.setVisibility(View.VISIBLE);
            }
        }

        showAlreadPairDevice();
    }

    /**
     * 显示已经配对设置
     */
    private void showAlreadPairDevice() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {// 把名字和地址取出来添加到适配器中
                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                Log.i(TAG, "showAlreadPairDevice: " + device.getName() + "  " + device.getAddress());
            }
        }
    }

    private void registerBlueToothBroadCast() {
        BroadcastReceiver blueToothValueReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, DEFAULT_VALUE_BULUETOOTH);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            Log.i(TAG, "onReceive: 蓝牙已关闭");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.i(TAG, "onReceive: 蓝牙已打开");
                            break;
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.i(TAG, "onReceive: 正在打开蓝牙");
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.i(TAG, "onReceive: 正在关闭蓝牙");
                            break;
                        default:
                            Log.i(TAG, "onReceive: 未知状态");
                    }
                } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//从 Intent 中获取发现的 BluetoothDevice
                    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());// 将名字和地址放入要显示的适配器中
                    Log.i(TAG, "onReceive: " + device.getName() + "  " + device.getAddress());
                    bluetoothDeviceList.add(device);
                    if ("Scanner_7AD0".equals(device.getName())) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                    Log.i(TAG, "搜索开启");
                } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                    Log.i(TAG, "搜索完成");
                } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                    //找到设备后获取其设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    switch (device.getBondState()) {
                        case BluetoothDevice.BOND_BONDING:
                            //正在配对
                            Log.i(TAG, "正在配对");
                            break;
                        case BluetoothDevice.BOND_BONDED:
                            //配对结束
                            Log.i(TAG, "配对结束");
                            BluetoothConnectThread bluetoothConnectThread = new BluetoothConnectThread(bluetoothDevice, new BluetoothConnectCallback() {
                                @Override
                                public void connectSuccess(BluetoothSocket socket) {
                                    bluetoothSocket = socket;
                                    listener();
                                }

                                @Override
                                public void connectFailed(String errorMsg) {
                                    Log.i(TAG, "connectFailed: " + errorMsg);
                                }

                                @Override
                                public void connectCancel() {
                                    Log.i(TAG, "connectCancel: ");
                                }
                            });
                            bluetoothConnectThread.start();
                            break;
                        case BluetoothDevice.BOND_NONE:
                            //取消配对/未配对
                            Log.i(TAG, "取消配对/未配对");
                        default:
                            break;
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(blueToothValueReceiver, filter);
    }

    private void listener() {
        try {
            InputStream inputStream = bluetoothSocket.getInputStream();

//            while (true) {
//                int size;
//                try {
//                    if (inputStream == null)
//                        return;
//                    byte[] buffer = new byte[512];
//                    size = inputStream.read(buffer);
//                    if (size != 0) {
//                        byte[] realBuffer = new byte[size];
//                        Log.i(TAG, "listener: " + realBuffer.toString());
//                    }
//                    Thread.sleep(100);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 手动配对
     */
    private void pair() {
        //手动配对，完成配对后重新扫描即可
        try {
            Method method = null;

            for (int i = 0; i < bluetoothDeviceList.size(); i++) {
                if ("Scanner_7AD0".equals(bluetoothDeviceList.get(i).getName())) {
                    bluetoothDevice = bluetoothDeviceList.get(i);
                    break;
                }
            }
            if (bluetoothDevice != null) {
                method = BluetoothDevice.class.getMethod("createBond");
                method.invoke(bluetoothDevice);
            } else {
                Log.i(TAG, "pair: device null");
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_blue_tooth: {
                if (!mBluetoothAdapter.isEnabled()) {
                    mBluetoothAdapter.enable();
                    btn_blue_tooth.setText("关闭蓝牙");
                    btn_check_new_devices.setVisibility(View.VISIBLE);
                } else {
                    mBluetoothAdapter.disable();
                    btn_blue_tooth.setText("打开兰蓝牙");
                    btn_check_new_devices.setVisibility(View.GONE);
                }
            }
            break;
            case R.id.btn_check_new_devices:
                boolean isStart = mBluetoothAdapter.startDiscovery(); //mBluetoothAdapter.cancelDiscovery();
                Log.i(TAG, "onClick: " + isStart);
                break;
            case R.id.btn_pair:
                pair();
                break;
        }
    }
}
